package com.ynny.librarysystemmanager.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.ynny.librarysystemmanager.common.BookReturnCode;
import com.ynny.librarysystemmanager.common.BookStatus;
import com.ynny.librarysystemmanager.common.CommonReturnCode;
import com.ynny.librarysystemmanager.common.UserReturnCode;
import com.ynny.librarysystemmanager.entity.Book;
import com.ynny.librarysystemmanager.entity.Record;
import com.ynny.librarysystemmanager.entity.User;
import com.ynny.librarysystemmanager.mapper.BookMapper;
import com.ynny.librarysystemmanager.mapper.RecordMapper;
import com.ynny.librarysystemmanager.mapper.UserMapper;
import com.ynny.librarysystemmanager.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@Service
public class RecordServiceImpl implements RecordService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    BookMapper bookMapper;

    @Autowired
    RecordMapper recordMapper;


    private static final String BORROW_FLAG = "sub";
    private static final String RETURN_FLAG = "add";


    @Transactional
    @Override
    public int borrowBook(Integer userId, Integer bookId) {
        //借书逻辑
        /*
        校验
        1.借阅人 ----》 用户是否存在  权限  是否可用
        2.图书  -----》 图书是否存在  是否可用   库存是否充足


        3.借阅记录是否存在 ------- 不允许重复借同一本书


        操作
        4.记录 借阅人 借阅图书 归还时间
          库存 -1
         */

        //校验借阅人 是否存在
        User borrowerUser = userMapper.selectOne(userId);
        // 251 ----》查询用户为空
        if (borrowerUser == null){
            return UserReturnCode.USER_IS_NULL;
        }
        //是否可用
        if (borrowerUser.getIsDelete().equals(1)){
            return UserReturnCode.USER_IS_DELETE;
        }
        //权限是否可用   ----》 学生 老师  管理员   游客
        if (borrowerUser.getRole().getRoleId().equals(4)){
            return UserReturnCode.USER_IS_NOT_IDENTITY;
        }

        //校验图书
        Book borrowerBook = bookMapper.selectOne(bookId);
        if (borrowerBook == null){
            return BookReturnCode.BOOK_IS_NULL;
        }

        if (borrowerBook.getIsDelete().equals(1)){
            return BookReturnCode.BOOK_IS_DELETE;
        }

        if (borrowerBook.getStorage() <= 0){
            return BookReturnCode.BOOK_IS_NOT_STORAGE;
        }


        Record record = recordMapper.selectRecordByUserIdAndBookId(userId, bookId);

        if (record != null){
            return BookReturnCode.BOOK_IS_BORROWED;
        }

        Record newRecord = new Record();
        newRecord.setBorrowerId(userId);
        newRecord.setBorrowerName(borrowerUser.getName());
        newRecord.setBookId(bookId);
        newRecord.setBookName(borrowerBook.getBookName());
        newRecord.setBorrowTime(LocalDateTime.now());
        //最后归还(预取时间)时间

        LocalDateTime offset = LocalDateTimeUtil
                .offset(LocalDateTime.now(), 1, ChronoUnit.MONTHS);
        newRecord.setEndTime(offset);
        //新增一条借阅记录 状态默认就是  借阅中
        newRecord.setStatus(BookStatus.Borrowing.getCode());

        //添加借阅信息 成功 后 修改图书库存
        int i = recordMapper.insertRecord(newRecord);

        if (i > 0 ){
            int j = bookMapper.updateBookStorage(bookId, BORROW_FLAG);
            return j > 0 ? CommonReturnCode.SERVER_SUCCESS_CODE : CommonReturnCode.SERVER_ERROR_CODE;
        } else {
            return CommonReturnCode.SERVER_ERROR_CODE;
        }

    }

    @Override
    public int returnBook(Integer userId, Integer bookId) {

        //归还逻辑
        /**
         * 校验
         * 1. 归还的图书是否存在
         *
         * 2. 图书是否可用
         *
         * 3. 超出归还时间 ---->  给这个用户
         *                      记录 逾期次数  3次(信用值) 不允许再借书
         *                      账户就不可用
         * 4. 用户是否可用
         *    用户是否还有信用
         * 操作
         *
         * 5. 借阅借阅 修改借阅信息  归还时间 借阅状态
         *    图书库存 +1

         */
        //校验借阅人 是否存在
        User borrowerUser = userMapper.selectOne(userId);

        if (borrowerUser == null){
            return UserReturnCode.USER_IS_NULL;
        }
        //是否可用
        if (borrowerUser.getIsDelete().equals(1)){
            return UserReturnCode.USER_IS_DELETE;
        }
        //权限是否可用   ----》 学生 老师  管理员   游客
        if (borrowerUser.getRole().getRoleId().equals(4)){
            return UserReturnCode.USER_IS_NOT_IDENTITY;
        }

        //校验图书
        Book borrowerBook = bookMapper.selectOne(bookId);
        if (borrowerBook == null){
            return BookReturnCode.BOOK_IS_NULL;
        }

        if (borrowerBook.getIsDelete().equals(1)){
            return BookReturnCode.BOOK_IS_DELETE;
        }


        //校验图书是否可以归还
        Record record = recordMapper
                .selectRecordByUserIdAndBookId(userId, bookId);

        if (record == null){
            return BookReturnCode.BOOK_IS_NOT_BORROWED;
        }

        if (record.getStatus().equals(BookStatus.Overdue.getCode())){
            //账户不可用
            userMapper.deleteUser(userId, 1);
        }else {
            record.setStatus(BookStatus.Returned.getCode());
        }

//        Duration between = LocalDateTimeUtil
//                .between(LocalDateTime.now(),
//                record.getEndTime());
//
//        long days = between.toDays();
//        if (days < 0){
            //逾期后
            //账户不可用
//            userMapper.deleteUser(userId, 1);
//            record.setStatus(BookStatus.Overdue.getCode());
//        }else {
//            record.setStatus(BookStatus.Returned.getCode());
//        }
        //修改借阅信息
        record.setReturnTime(LocalDateTime.now());

        int i = recordMapper.updateRecord(record);
        if (i > 0){
            //修改图书库存
            int j = bookMapper.updateBookStorage(bookId, RETURN_FLAG);
            return j > 0 ? CommonReturnCode.SERVER_SUCCESS_CODE : CommonReturnCode.SERVER_ERROR_CODE;
        }else {
            return CommonReturnCode.SERVER_ERROR_CODE;
        }

    }


}


